package com.boruishangge.common.http;


import android.text.TextUtils;


import com.boruishangge.common.Interface.aplusApi;
import com.boruishangge.persagysdk.base.BaseActivity;
import com.boruishangge.persagysdk.base.BaseConstant;
import com.boruishangge.persagysdk.entiy.BaseModel;
import com.boruishangge.persagysdk.network.HttpsUtils;
import com.boruishangge.persagysdk.network.LoggerInterceptor;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.trello.rxlifecycle2.LifecycleTransformer;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

import io.reactivex.Observable;
import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import io.reactivex.Observer;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * TODO 网络访问入口
 */
public class RetrofitFactory {

    private static final long TIMEOUT = 30;
    private static OkHttpClient okHttpClient;
   private static final  Gson mGson=new Gson();
    private static aplusApi mApiPlus;

      public static Gson getGson(){
         return  mGson;
          }


        public static OkHttpClient getOkHttpClient() {
        if (okHttpClient!=null){
            return okHttpClient;
        }
        //如果不是http 请求不要打开
        HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(null, null, null);
          okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(TIMEOUT, TimeUnit.SECONDS)
                .addInterceptor(new LoggerInterceptor("aplus----Net"))
                .hostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                })
//                .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager)
                .build();
        return okHttpClient;
    }
    public static synchronized aplusApi getInstance() {
          if (mApiPlus==null){
            String  BASE_URL = "http://" + BaseConstant.ServerIP + "/";
              mApiPlus= new Retrofit.Builder()
                      .client(getOkHttpClient())
                      .addConverterFactory(GsonConverterFactory.create(createGSon()))
                      .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                      .baseUrl(BASE_URL)
                      .build().create(aplusApi.class);
          }
          return  mApiPlus;
    }
    private static Gson createGSon() {
        return new GsonBuilder()
                .serializeNulls()
                .setDateFormat("yyyy-MM-dd HH:mm:ss")
                .setFieldNamingPolicy(FieldNamingPolicy.IDENTITY)
                .create();
    }




    /**
     * @param requestBean
     * @param <T>
     * @return
     */
    public static  <T> RequestBody getRequestBody(T requestBean) {
        String params, contentType = "";
        if (requestBean instanceof JSONObject) {
            JSONObject jsonObject = (JSONObject) requestBean;
            try {
                if (!TextUtils.isEmpty(BaseConstant.pdMD5Code)) {
                    jsonObject.put(BaseConstant.PD, BaseConstant.pdMD5Code);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            params = jsonObject.toString();
        } else if (requestBean instanceof HashMap) {
            HashMap<Object, Object> hashMap = (HashMap<Object, Object>) requestBean;
            hashMap.put(BaseConstant.PD, BaseConstant.pdMD5Code);
            params = getGson().toJson(hashMap);
        } else {
            params = getGson().toJson(requestBean);
        }
          contentType = "application/json";

        RequestBody body = RequestBody.create(MediaType.parse(contentType), params);
        return body;
    }


        //====================================待办部分 end============================================
        public static  <S> void sendRequest(Observable<BaseModel<S>> observable,
                                       Observer<? super BaseModel<S>> observer, BaseActivity mActivity) {////绑定生命周期，防止内存泄露

            observable.compose(compose(mActivity.<BaseModel<S>>bindToLifecycle())).subscribe( observer);

     }

    public static  <T> ObservableTransformer<T, T> compose(final LifecycleTransformer<T> lifecycle) {
        return observable
                -> observable
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> { })
                .observeOn(AndroidSchedulers.mainThread())
                .compose(lifecycle);
    }

}
